package com.soujiayi.activity;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.GridView;
import android.widget.ListView;

import com.soujiayi.adapter.ProductClassifyExpandableListAdapter;
import com.soujiayi.adapter.ProductClassifyGridViewAdapter;
import com.soujiayi.adapter.SearchListAdapter;
import com.soujiayi.model.Category;
import com.soujiayi.model.Categorys;
import com.soujiayi.net.AsyncSuggestionNameLoader;
import com.soujiayi.net.HttpRequester;
import com.soujiayi.net.NetworkUtils;
import com.soujiayi.store.DatabaseManager;
import com.soujiayi.util.CommonUtils;
import com.soujiayi.util.Constants;

public class SearchActivity extends Activity implements OnClickListener,
		OnItemClickListener, OnFocusChangeListener, TextWatcher {
	private EditText searchText;
	private Button searchBtn;
	private ListView searchListView;
	private SearchListAdapter searchListAdapter;
	private ArrayList<HashMap<String, Object>> searchList = new ArrayList<HashMap<String,Object>>();
	private DatabaseManager databaseManager = new DatabaseManager(SearchActivity.this);
	private Handler handler;
	private AsyncSuggestionNameLoader asyncSuggestionNameLoader = new AsyncSuggestionNameLoader(3);
	private String cancel;
	private String search;
	private boolean isClassifyShowed = false;
	private boolean isFirstShow = true;
	private GridView classifyGridView;
	private ProductClassifyGridViewAdapter classifyGridViewAdapter;
	private List<Integer> classifyImageData;
	private List<Category> classifyTextData;
	private ExpandableListView classifyExpandableListView;
	private ProductClassifyExpandableListAdapter classifyExpandableListAdapter;
	private List<String> classifyExpandableListGroupData;
	private List<ArrayList<Category>> classifyExpandableListChildData;
	private Button backBtn;
	private HttpRequester httpRequester;
	private Handler searchCategoryHandler;
	private boolean isSubCategory = false;
	private String sid = "";
	private LinearLayout ll_data_loading;
	private LinearLayout ll_reload;
	private ProgressDialog progressDialog;
	private String parityGroupName = "";
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		((MyApplication) this.getApplication()).addActivity(this);
		setContentView(R.layout.product_search);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 
		
		
		searchListView = (ListView) findViewById(R.id.search_history_suggestion_listview);
		searchListAdapter = new SearchListAdapter(this,searchList);
        searchListView.setAdapter(searchListAdapter);
        searchListView.setOnItemClickListener(this);
		searchBtn = (Button) findViewById(R.id.search_searchBtn);
		searchBtn.setOnClickListener(this);
		searchText = (EditText) findViewById(R.id.search_searchText);
		searchText.addTextChangedListener(this);
		searchText.setOnFocusChangeListener(this);
		
		// 当滚动时收起软键盘
        searchListView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(searchText.getWindowToken(), 0); 
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		});
		
		cancel = this.getResources().getString(R.string.cancel);
		search = this.getResources().getString(R.string.search);
		
		backBtn	= (Button) findViewById(R.id.search_backBtn);
		
		handler = new Handler(){
		    @Override
		    public void handleMessage(Message msg) {
		        super.handleMessage(msg);
		        Bundle data = msg.getData();
		        if(data.getStringArrayList("keys").size() > 1){
		        	searchList.removeAll(searchList);
		        	searchList.addAll(CommonUtils.convertLStrToLMap(data.getStringArrayList("keys")));
		        	searchListAdapter.notifyDataSetChanged();
		        }
		    }
		};		
		
		Intent intent = this.getIntent();
		isClassifyShowed = intent.getBooleanExtra(Constants.PRODUCT_IS_CLASSIFY_SHOWED, false);
		if(isClassifyShowed){
			initClassifyGridView();
		}
		
		if(isSubCategory){
			backBtn.setBackgroundResource(R.drawable.arrow_left);
		}else{
			backBtn.setBackgroundResource(R.drawable.home_icon);
		}
	}
	
	// 初始化分类搜索视图
	private void initClassifyGridView(){
		ll_data_loading = (LinearLayout) findViewById(R.id.ll_data_loading);
		ll_reload = (LinearLayout) findViewById(R.id.ll_click_to_reload);
		searchCategoryHandler = new Handler(){
		    @Override
		    public void handleMessage(Message msg) {
		        super.handleMessage(msg);
		        Bundle data = msg.getData();
		        
		        ll_data_loading.setVisibility(View.GONE);
		        progressDialog.cancel();
		        boolean isError = data.getBoolean(Constants.IS_ERROR);
		        if(isError){
		        	ll_reload.setVisibility(View.VISIBLE);
		        	
					Toast.makeText(
							SearchActivity.this,
							SearchActivity.this.getString(R.string.load_data_failure),
							Toast.LENGTH_LONG).show();
		        	return;
		        }else{
		        	ll_reload.setVisibility(View.GONE);
		        }

		        Categorys categorys = (Categorys) data.getSerializable(Constants.CATEGORYS);
		        List<Category> categoryList = categorys.getCategorys();
		        
		        int type = data.getInt(Constants.CATEGORYS_TYPE);
		        switch(type){
		        case Constants.CATEGORYS_TYPE_ROOT:
			        if(categoryList != null && categoryList.size() > 0){
				        for(Category category : categoryList){
				        	classifyTextData.add(category);
				        }
				        classifyGridViewAdapter.notifyDataSetChanged();
			        }
			        break;
		        case Constants.CATEGORYS_TYPE_SUB:
		        	if(categoryList != null && categoryList.size() > 0){
		        		//classifyExpandableListGroupData.addAll(secondCategorys);
		        		
						classifyGridView.setVisibility(View.INVISIBLE);
						classifyExpandableListView.setVisibility(View.VISIBLE);
						classifyExpandableListGroupData.removeAll(classifyExpandableListGroupData);
						classifyExpandableListGroupData.add(parityGroupName);
						classifyExpandableListChildData.removeAll(classifyExpandableListChildData);
						backBtn.setBackgroundResource(R.drawable.arrow_left);
						
						ArrayList<ArrayList<Category>> subCategoryList = new ArrayList<ArrayList<Category>>();
						subCategoryList.add((ArrayList<Category>) categoryList);
						isSubCategory = true;
		        		classifyExpandableListChildData.addAll(subCategoryList);
						classifyExpandableListAdapter.notifyDataSetChanged();
						for(int i = 0; i < classifyExpandableListAdapter.getGroupCount(); i ++){
							classifyExpandableListView.expandGroup(i);
						}
		        	}
		        	break;
		        default:
		        	break;
		        }
		    }
		};
		sid = ((MyApplication)this.getApplication()).getSessionId();
		httpRequester = new HttpRequester(this,1, searchCategoryHandler);
		if(!NetworkUtils.isNetworkConnected(SearchActivity.this)){
			ll_reload.setVisibility(View.VISIBLE);			
			Toast.makeText(
					SearchActivity.this,
					SearchActivity.this
							.getString(R.string.network_unavailable_message),
					Toast.LENGTH_LONG).show();
		}else{
			ll_data_loading.setVisibility(View.VISIBLE);
			httpRequester.getGoodsCategory(sid, "0", Constants.CATEGORYS_TYPE_ROOT);
		}
		
		
		classifyGridView = (GridView)findViewById(R.id.product_classify_gridview);
		
		classifyImageData = new ArrayList<Integer>();
		classifyTextData = new ArrayList<Category>();
		
		classifyGridViewAdapter = new ProductClassifyGridViewAdapter(this, classifyImageData, classifyTextData);	
		classifyGridView.setAdapter(classifyGridViewAdapter);
		
		
		classifyExpandableListView = (ExpandableListView) findViewById(R.id.product_classify_expandableListView);
		
		classifyExpandableListGroupData = new ArrayList<String>();
		classifyExpandableListChildData = new ArrayList<ArrayList<Category>>();
		classifyExpandableListAdapter = new ProductClassifyExpandableListAdapter(this, classifyExpandableListGroupData,  classifyExpandableListChildData);
		
		classifyExpandableListView.setAdapter(classifyExpandableListAdapter);
		
		classifyExpandableListView.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				isClassifyShowed = true;
				doSearch(classifyExpandableListChildData.get(groupPosition).get(childPosition).getName(),classifyExpandableListChildData.get(groupPosition).get(childPosition).getCatid());
				return false;
			}
		});
		
		classifyGridView.setSelected(true);
		
		classifyGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View item, int position, long arg3) {	
				if(!NetworkUtils.isNetworkConnected(SearchActivity.this)){
					Toast.makeText(
							SearchActivity.this,
							SearchActivity.this
									.getString(R.string.network_unavailable_message),
							Toast.LENGTH_LONG).show();
					return;
				}
				
				classifyExpandableListView.setVisibility(View.INVISIBLE);
				parityGroupName = classifyTextData.get(position).getName();
				progressDialog.show();
				httpRequester.getGoodsCategory(sid, classifyTextData.get(position).getCatid(), Constants.CATEGORYS_TYPE_SUB);
			}		
		});
		
		progressDialog = new ProgressDialog(SearchActivity.this);
		progressDialog.setMessage(getResources().getString(R.string.progress_loading_data));
		Window window = progressDialog.getWindow();   
	    WindowManager.LayoutParams lp = window.getAttributes();   
	    lp.alpha = 0.7f;// 透明度   
	    lp.dimAmount = 0.5f;// 黑暗度   
	    window.setAttributes(lp); 
	}

	@Override
	public void afterTextChanged(Editable s) {
		if(!NetworkUtils.isNetworkConnected(this)){
			Toast.makeText(
					SearchActivity.this,
					SearchActivity.this
							.getString(R.string.network_unavailable_message),
					Toast.LENGTH_LONG).show();
			return;
		}
		
		String key = searchText.getText().toString().trim();
		if(isClassifyShowed){
			classifyGridView.setVisibility(View.INVISIBLE);
			classifyExpandableListView.setVisibility(View.INVISIBLE);
			searchListView.setVisibility(View.VISIBLE);
		}
		if(null == key || "".equals(key)){
			showHistory();
		}else{
			showSuggestionNames(key);
		}
		searchBtn.setText(cancel);
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.search_searchBtn: {
			if(searchBtn.getText().equals(search)){
				String key = searchText.getText().toString();
				if(null != key && !"".equals(key.trim())){
					databaseManager.insertSearchHistory(key,Constants.HISTORY_TYPE_PRODUCT);
					doSearch(key);
				}
			}else if(searchBtn.getText().equals(cancel)){
				if(isClassifyShowed){
					searchListView.setVisibility(View.INVISIBLE);
					classifyExpandableListView.setVisibility(View.INVISIBLE);
					classifyGridView.setVisibility(View.VISIBLE);
					searchBtn.setText(search);
				}else{
					Intent intent = new Intent(SearchActivity.this, IndexActivity.class);
					startActivity(intent);
				}
			}
		}
			break;
		default:
			break;
		}
	}
	
	// 搜索商品 跳转到商品列表视图
	public void doSearch(String key){
		Intent intent = new Intent(SearchActivity.this, ProductMainActivity.class);
		intent.putExtra(Constants.SEARCH_INTENT_KEY, key);
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}
	
	public void doSearch(String key, String cid){
		Intent intent = new Intent(SearchActivity.this, ProductMainActivity.class);
		intent.putExtra(Constants.SEARCH_INTENT_KEY, key);
		intent.putExtra(Constants.PRODUCT_CID, cid);
		intent.putExtra(Constants.PRODUCT_IS_CLASSIFY_SHOWED, true);
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	// 当搜索框获取焦点时显示历史记录
	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		if (v.getId() == R.id.search_searchText && hasFocus) {
			showHistory();
		}
	}
	
	// 获取联想词
	private void showSuggestionNames(String key){
		if(NetworkUtils.isNetworkConnected(this)){
			searchList.removeAll(searchList);
			HashMap<String,Object> map = new HashMap<String,Object>();
			map.put(Constants.SEARCH_LIST_ITEM, key);
			searchList.add(map);
			searchListAdapter.notifyDataSetChanged();
			asyncSuggestionNameLoader.getSuggestioName(this.handler, key);
		}else{
			Toast.makeText(
					SearchActivity.this,
					SearchActivity.this
							.getString(R.string.network_unavailable_message),
					Toast.LENGTH_LONG).show();
		}
	}

	// 显示历史记录
	private void showHistory() {
		if(isClassifyShowed){
			if(isFirstShow){// 如果当前是分类搜索视图而且是第一次显示 不显示历史记录
				searchListView.setVisibility(View.INVISIBLE);
				isFirstShow = false;
				return;
			}else{
				searchListView.setVisibility(View.VISIBLE);
				if(classifyGridView != null){// 隐藏分类搜索
					classifyGridView.setVisibility(View.INVISIBLE);
					classifyExpandableListView.setVisibility(View.INVISIBLE);
				}
			}
		}
		
		String key = searchText.getText().toString();
		if (null == key || "".equals(key.trim())) {
			ArrayList<HashMap<String,Object>> history = databaseManager.getSearchHistory(Constants.HISTORY_TYPE_PRODUCT);
			if (history.size() > 0) {
				searchList.removeAll(searchList);
				searchList.addAll(history);
				HashMap<String,Object> map = new HashMap<String,Object>();
				map.put(Constants.SEARCH_LIST_ITEM, Constants.SEARCH_LIST_CLEAR_HISTORY_ITEM); 
				searchList.add(map);
				searchListAdapter.notifyDataSetChanged();
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				if (imm.isActive()) {
					imm.hideSoftInputFromWindow(SearchActivity.this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
				}
			}else{
				donotShowHistory();
			}
		}
	}

	private void donotShowHistory() {
		searchList.removeAll(searchList);
		searchListAdapter.notifyDataSetChanged();
	}

	// 点击历史记录或联想词搜索商品
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		String selectedKey = searchList.get(arg2).get(Constants.SEARCH_LIST_ITEM).toString().trim();
		if (null != selectedKey && !selectedKey.equals("")) {
			if (selectedKey.equals(Constants.SEARCH_LIST_CLEAR_HISTORY_ITEM)) {
				databaseManager.deleteSearchHistory(Constants.HISTORY_TYPE_PRODUCT);
				donotShowHistory();
			} else {
				databaseManager.insertSearchHistory(selectedKey,Constants.HISTORY_TYPE_PRODUCT);
				doSearch(selectedKey);
			}
		}
	}
	
	public void reload(View view){
		if(NetworkUtils.isNetworkConnected(this)){
			ll_reload.setVisibility(View.GONE);
			ll_data_loading.setVisibility(View.VISIBLE);
			httpRequester.getGoodsCategory(sid, "0", Constants.CATEGORYS_TYPE_ROOT);
		}else{			
			Toast.makeText(
					SearchActivity.this,
					SearchActivity.this
							.getString(R.string.network_unavailable_message),
					Toast.LENGTH_LONG).show();
		}
	}
	
	@Override
	protected void onDestroy() {
		databaseManager.closeDB();
		asyncSuggestionNameLoader.close();
		if(httpRequester != null){
			httpRequester.close();
		}
		super.onDestroy();
	}
	
	// 返回首页
	public void backToHome(View view){
		Intent intent = new Intent(SearchActivity.this, IndexActivity.class);
		startActivity(intent);
		this.finish();
		if(isClassifyShowed){			
			overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
		}
	}
	
	// 分类搜索返回
	public void back(View view){
		if(isSubCategory){
			classifyGridView.setVisibility(View.VISIBLE);
			classifyExpandableListView.setVisibility(View.INVISIBLE);
			backBtn.setBackgroundResource(R.drawable.home_icon);
			isSubCategory = false;
		}else{
			Intent intent = new Intent(SearchActivity.this, IndexActivity.class);
			startActivity(intent);
			if(isClassifyShowed){
				this.finish();
				overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
			}
		}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		//如果按下的是返回键，并且没有重复
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			if(isClassifyShowed){
				overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
			}
			return false;
		}
		return false;
	}
	
}
